<template>
  <div class="table-container">
    <div class="tools">
      <button @click="invertSelection" style="margin-right: 10px;">反选</button>
      <button @click="deleteSelectedUsers" style="margin-right: 10px;">删除</button>
      <button @click="openTypeDialog" style="margin-right: 10px;">指定类型</button>
      <select v-model="condition.type">
        <template v-for="(item, index) in userTypes" :key="index">
          <option :value="item.value">{{ item.label }}</option>
        </template>
      </select>
    </div>
    <table>
      <thead>
        <tr>
          <th>
            <span>
              <input type="checkbox" :checked="isAllSelected" @change="toggleSelectAll" />
            </span>
            <span>账号</span>
          </th>
          <th>电子邮件</th>
          <th>用户类型</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>

        <tr v-for="(user, index) in filteredUsers" :key="index">
          <td>
            <span><input type="checkbox" v-model="checkedUserNames" :value="user.username" /></span>
            <span>{{index+1}}  、 {{ user.username }}</span>
          </td>
          <td>{{ user.email }}</td>
          <td>{{ getUserTypeLabel(user.type) }}</td>
          <td>
            <div style="display: flex;">
              <button @click="deleteUser(index)" style="background-color: #ff2a2e;">删除</button>
            </div>

          </td>
        </tr>
      </tbody>
    </table>

    <!-- 弹窗层 显示用户类型 -->
    <div v-if="showDialog" class="dialog-overlay">
      <div class="dialog">
        <h3>指定用户类型</h3>

        <select v-model="selectedType" style="margin: 12px 0;">
          <option v-for="(item, i) in userTypes" :key="i" :value="item.value">
            {{ item.label }}
          </option>
        </select>

        <div class="dialog-buttons">
          <button @click="confirmChangeType">确定</button>
          <button @click="closeDialog" style="background-color: gray;">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入 user 模块导出默认对象，并使用别名 UserApi
import { computed, reactive, ref } from "vue";
import UserApi, { userType, getUserTypeLabel, userTypes } from "../../api/user";

// 定义用户数据，调用api，初始化变量: users。由于 fetchUsers() 返回的是reactive函数结果，是一个响应式对象。因此 users 是对该对象的引用。
const users = UserApi.fetchUsers();

// 选中的用户username数组，选择状态围绕数组的值进行
const checkedUserNames = ref([])

// 筛选条件
const condition = reactive({
  type: userType.all,
  keyword: ''
})

// 过滤用户列表，使用计算属性
const filteredUsers = computed(() => {
  if (condition.type === userType.all) return users
  return users.filter(u => u.type === condition.type)
})

// 全选复选框的选中状态判断
const isAllSelected = computed(() => {
  return filteredUsers.value.length > 0 && checkedUserNames.value.length === filteredUsers.value.length;
})

// 全选和取消全选的切换
const toggleSelectAll = (event) => {
  if (event.target.checked) {
    checkedUserNames.value = filteredUsers.value.map(u => u.username);
  } else {
    checkedUserNames.value = [];
  }
}

// 反选
const invertSelection = () => {
  checkedUserNames.value = filteredUsers.value
    .filter(u => !checkedUserNames.value.includes(u.username))
    .map(u => u.username)
    .concat(
      checkedUserNames.value.filter(username => !filteredUsers.value.some(u => u.username === username))
    );
}

// 弹窗层的控制显示
const showDialog = ref(false);
const selectedType = ref(userType.all);

// 打开弹窗
const openTypeDialog = () => {
  if (checkedUserNames.value.length === 0) {
    alert("请先选择要修改的用户！");
    return;
  }
  selectedType.value = userType.all;
  showDialog.value = true;
};

// 关闭弹窗
const closeDialog = () => {
  showDialog.value = false;
};

// 点击确定按钮
const confirmChangeType = () => {

  // 修改用户属性
  users.forEach((user) => {
    if (checkedUserNames.value.includes(user.username)) {
      user.type = selectedType.value;
    }
  });

  // 回复数据状态
  checkedUserNames.value = []
  selectedType.value = userType.all
  // 关闭弹窗
  showDialog.value = false;
};


const deleteSelectedUsers = () => {
  // 选择的用户
  if (checkedUserNames.value.length > 0) {
    if (confirm(`要删除 ${checkedUserNames.value.length} 个用户?`)) {

      // 遍历删除
      checkedUserNames.value.forEach(username => {
        UserApi.deleteByUsername(username)
      });

      // 清空选择
      checkedUserNames.value = [];
    }
  }
}

// 删除用户
const deleteUser = (index) => {
  if (confirm("要删除该用户? ")) {
    const user = users[index];
    // 调用接口，现场远程数据。可以为 deleteByUsername 设计一个回调函数参数，可以获得更多的参数，从而能够增强下一步的逻辑处理能力 ，而不是仅能通过 true 和 false。
    if (UserApi.deleteByUsername(user.username)) {
      //console.log("当前页面组件users: ", users);
      //console.log("js文件中userList: ", UserApi.fetchUsers());

    }
  }
};

</script>

<style scoped>
.table-container {
  display: flex;
  flex-direction: column;
  /* 按列排列 */
  align-items: flex-end;
  /* 左对齐 */
  width: 550px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.tools {
  margin-bottom: 12px;
}

table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

th,
td {
  padding: 10px;
  text-align: left;
  border-bottom: 1px solid #ddd;
}

th {
  background-color: #f4f4f4;
}

button {
  padding: 5px 10px;
  background-color: blueviolet;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}


/* ✅ 弹窗样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.45);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.dialog {
  background: #fff;
  padding: 20px 30px;
  border-radius: 10px;
  min-width: 300px;
  text-align: center;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
}

.dialog-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 12px;
}
</style>
